﻿@page "/devicelist"
@using System.Net.Http.Json
@using IotClientApp.Client.Pages.Dialog;
@using IotClientApp.Shared
@using Newtonsoft.Json;
@inject HttpClient httpClient
@inject IDialogService DialogService
@inject NavigationManager Navigation

<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="AddDevice">新增</MudButton>
<MudTable Items="@Elements" Breakpoint="Breakpoint.Sm" LoadingProgressColor="Color.Info">
    <HeaderContent>
        <MudTh>Name</MudTh>
        <MudTh>Desc</MudTh>
        <MudTh>CreateTime</MudTh>
        <MudTh>操作</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Name">@context.Name</MudTd>
        <MudTd DataLabel="Desc">@context.Desc</MudTd>
        <MudTd DataLabel="CreateTime">@context.CreateTime</MudTd>
        <MudTd>
            <MudButton Variant="Variant.Filled" OnClick="@(() => {
                EditRow(context);
            })">编辑</MudButton>
            &nbsp;
            <MudButton Variant="Variant.Filled" OnClick="@(() => {
                EnableDeivce(context);
            })">
                @if (context.IsActive)
                {
                    <label>禁用</label>
                }
                else
                {
                    <label>启用</label>
                }
            </MudButton>
        </MudTd>
    </RowTemplate>

    <PagerContent>
        <MudPagination SelectedChanged="PageChanged" Count="@pageCount" Class="pa-4" />
    </PagerContent>
</MudTable>

@code {
    private List<DeviceInfoModel> Elements = new List<DeviceInfoModel>();
    private bool _readOnly;
    private bool _isCellEditMode;
    private List<string> _events = new();
    private bool _editTriggerRowClick;
    private int pageCount;
    private int pageSize = 20;
    private int pageIndex = 1;
    protected override async Task OnInitializedAsync()
    {
        await LoadData(pageIndex);
    }
    private async void AddDevice()
    {
        await EditRow(new DeviceInfoModel { });
    }
    private async Task EnableDeivce(DeviceInfoModel deviceInfo)
    {
        var response = await httpClient.GetStringAsync($"api/Device/EnableDevice?deviceId={deviceInfo.Id}&isActive={(!deviceInfo.IsActive).ToString().ToLower()}");
        Console.WriteLine(response);
        await LoadData(pageIndex);
    }

    private async Task EditRow(DeviceInfoModel deviceInfo)
    {
        var parameters = new DialogParameters<DeviceSave_Dialog> { { x => x.deviceInfo, deviceInfo }, { x => x.Title, "编辑" } };
        var dialog = await DialogService.ShowAsync<DeviceSave_Dialog>("编辑", parameters);
        var result = await dialog.Result;

        if (!result.Canceled)
        {
            Console.WriteLine("ok");
            await LoadData(pageIndex);
        }

        Console.WriteLine($"{deviceInfo.Name}");
    }
    private async Task LoadData(int pageIndex)
    {
        this.pageIndex = pageIndex;
        var response = await httpClient.PostAsJsonAsync("api/Device/GetDeviceInfos", new GetDeviceInfoModel
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceInfoModel>>(responseContent);
                Elements.Clear(); 
                if (result != null)
                {
                    Elements = result.Data;
                    pageCount = result.PageCount;
                }
                StateHasChanged();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    private async void PageChanged(int i)
    {
        await LoadData(i - 1);
    }
    // events
    void StartedEditingItem(DeviceInfoModel item)
    {
        _events.Insert(0, $"Event = StartedEditingItem, Data = {System.Text.Json.JsonSerializer.Serialize(item)}");
    }

    void CanceledEditingItem(DeviceInfoModel item)
    {
        _events.Insert(0, $"Event = CanceledEditingItem, Data = {System.Text.Json.JsonSerializer.Serialize(item)}");
    }

    void CommittedItemChanges(DeviceInfoModel item)
    {
        _events.Insert(0, $"Event = CommittedItemChanges, Data = {System.Text.Json.JsonSerializer.Serialize(item)}");
    }
}